<?php

namespace App\Exceptions;

use Exception;

/**
 * 业务异常类
 * 
 * 用于处理业务逻辑中的异常情况
 * 符合Laravel规范的自定义异常
 */
class BusinessException extends Exception
{
    /**
     * 创建业务异常实例
     * 
     * @param string $message 错误消息
     * @param int $code HTTP状态码
     * @param \Throwable|null $previous 前一个异常
     */
    public function __construct(string $message = '', int $code = 400, ?\Throwable $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }

    /**
     * 渲染异常为HTTP响应
     * 
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function render($request)
    {
        if ($request->expectsJson()) {
            return response()->json([
                'message' => $this->getMessage(),
                'error' => true
            ], $this->getCode());
        }

        return back()->with('error', $this->getMessage());
    }
}

